package com.pcg.posgasstation.view;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pcg.posgasstation.R;
import com.pcg.posgasstation.base.BaseActivity;
import com.pcg.posgasstation.interfaces.DialogCallback;
import com.pcg.posgasstation.model.Constant;
import com.pcg.posgasstation.model.network.ApiClient;
import com.pcg.posgasstation.model.network.entity.AddOrderEntity;
import com.pcg.posgasstation.model.network.entity.BaseEntity;
import com.pcg.posgasstation.model.network.entity.GoodsItemEntity;
import com.pcg.posgasstation.model.network.entity.MemberInfoEntity;
import com.pcg.posgasstation.utils.DialogHelper;
import com.pcg.posgasstation.utils.ToastUtils;
import com.pcg.posgasstation.utils.Utils;
import com.pcg.posgasstation.view.widget.DecimalInputTextWatcher;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class CreateOrderActivity extends BaseActivity {

    @BindView(R.id.layTvBack)
    ImageView mLayTvBack;
    @BindView(R.id.layBack)
    RelativeLayout mLayBack;
    @BindView(R.id.layTvTitle)
    TextView mLayTvTitle;
    @BindView(R.id.tvCarCard)
    TextView mTvCarCard;
    @BindView(R.id.tvCardNumber)
    TextView mTvCardNumber;
    @BindView(R.id.tvBalance)
    TextView mTvBalance;
    @BindView(R.id.tvBalanceInter)
    TextView mTvBalanceInter;
    @BindView(R.id.edtTotalMoney)
    EditText mEdtTotalMoney;
    @BindView(R.id.tvRealMoney)
    TextView mTvRealMoney;
    @BindView(R.id.tvDiscountAmount)
    TextView mTvDiscountAmount;
    @BindView(R.id.tvBuyAmount)
    TextView mTvBuyAmount;
    @BindView(R.id.tvGoodPrice)
    TextView mTvGoodPrice;
    @BindView(R.id.tvDiscountMoney)
    TextView mTvDiscountMoney;
    @BindView(R.id.btnPay)
    Button mBtnPay;
    @BindView(R.id.tvGoodName)
    TextView mTvGoodName;

    private GoodsItemEntity mGoodsItemEntity;
    private MemberInfoEntity mMemberInfoEntity;

    private double mRealTotalMoney = 0;
    private double mTotalMoney = 0;

    public static void startActivity(Context context, GoodsItemEntity itemEntity, MemberInfoEntity memberInfoEntity) {
        Intent intent = new Intent();
        intent.setClass(context, CreateOrderActivity.class);
        intent.putExtra("item_goods", itemEntity);
        intent.putExtra("member_info", memberInfoEntity);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_order);
        ButterKnife.bind(this);

        initData();
        initView();
    }

    private void initData() {
        mGoodsItemEntity = getIntent().getParcelableExtra("item_goods");
        mMemberInfoEntity = getIntent().getParcelableExtra("member_info");
    }

    private void initView() {
        mProgressDialog = new ProgressDialog(this);

        mEdtTotalMoney.addTextChangedListener(new DecimalInputTextWatcher(mEdtTotalMoney, 10, 2) {
            @Override
            public void afterTextChanged(Editable editable) {
                super.afterTextChanged(editable);
                String money = mEdtTotalMoney.getText().toString();
                calculateCurrentMoney(money);
            }
        });

        mLayTvTitle.setText("创建订单");
        if (mMemberInfoEntity != null) {
            mTvCarCard.setText(mMemberInfoEntity.getCar_card());
            mTvCardNumber.setText("卡号：" + mMemberInfoEntity.getMembers_card());
            mTvBalance.setText("余额：" + mMemberInfoEntity.getBalance());
            mTvBalanceInter.setText("积分：" + String.valueOf(mMemberInfoEntity.getBalance_inter()));
        }
    }

    private void calculateCurrentMoney(String money) {
        double moneyNumber;
        try {
            if (TextUtils.isEmpty(money)) {
                moneyNumber = 0;
            } else {
                moneyNumber = Double.parseDouble(money);
            }
            mTotalMoney = moneyNumber;
            if (mGoodsItemEntity != null) {
                double foodPrice = Double.parseDouble(mGoodsItemEntity.getFood_price());
                double foodAmount = Double.parseDouble(mGoodsItemEntity.getFood_amount());

                double count = moneyNumber / foodPrice;
                double discountMoney = foodAmount * count;
                BigDecimal bigDecimal = new BigDecimal(discountMoney);
                BigDecimal newDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_DOWN);
                discountMoney = newDecimal.doubleValue();

                mTvDiscountMoney.setText(mGoodsItemEntity.getFood_amount() + "元/" + mGoodsItemEntity.getFood_unit());
                mTvGoodPrice.setText(mGoodsItemEntity.getFood_price() + "元/" + mGoodsItemEntity.getFood_unit());
                mTvGoodName.setText(mGoodsItemEntity.getFood_name());
                BigDecimal b = new BigDecimal(count);
                //保留2位小数
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                mTvBuyAmount.setText(String.valueOf(f1) + "L");

                mTvDiscountAmount.setText(String.valueOf(discountMoney) + "元");
                mRealTotalMoney = moneyNumber - discountMoney;
                mTvRealMoney.setText(String.valueOf(mRealTotalMoney) + "元");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.layBack)
    void backClick() {
        finish();
    }

    @OnClick(R.id.btnPay)
    void payMoney() {
        if (mTotalMoney <= 0) {
            ToastUtils.showToast("请输入金额");
            return;
        }
        createOrder(mMemberInfoEntity.getTel(), String.valueOf(mGoodsItemEntity.getId()), String.valueOf(mTotalMoney), mMemberInfoEntity.getMembers_card(), mGoodsItemEntity.getFood_name() + mGoodsItemEntity.getType_name());
    }

    private void createOrder(String phone, String food_id, final String realTotalMoney, final String members_card, final String foodName) {
        mProgressDialog.show();
        ApiClient.getApiService()
                .addOrder(ApiClient.getToken(), phone, food_id, realTotalMoney, members_card)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity<AddOrderEntity>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseEntity<AddOrderEntity> entity) {
                        mProgressDialog.hide();
                        if (entity != null) {
                            if (entity.isSuccess()) {
                                showVerifyPasswordDialog(entity.getData().getOrder_sn(), members_card, foodName, realTotalMoney);
                            } else {
                                ToastUtils.showToast(entity.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mProgressDialog.hide();
                        ToastUtils.showToast("创建订单失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private Dialog mVerifyPasswordDialog;

    private void showVerifyPasswordDialog(final String order_sn, final String members_card,
                                          final String goodName, final String realMoney) {
        mVerifyPasswordDialog = DialogHelper.getInstance()
                .showPayPasswordDialog(mContext, new DialogCallback() {
                    @Override
                    public void onConfirm(String text) {
                        if (TextUtils.isEmpty(text)) {
                            return;
                        }
//                checkPayPassword(order_sn, members_card, text, goodName, realMoney);

                        // test data
                        checkPayPassword(order_sn, members_card, text, goodName, realMoney);
                    }

                    @Override
                    public void onCancel() {
                        if (mVerifyPasswordDialog != null && mVerifyPasswordDialog.isShowing()) {
                            mVerifyPasswordDialog.dismiss();
                        }
                    }
                });
    }

    private void checkPayPassword(final String order_sn, final String members_card, String password,
                                  final String goodName, final String realMoney) {
        mProgressDialog.show();
        ApiClient.getApiService().verifyPassword(ApiClient.getToken(), order_sn, members_card,
                Utils.encryptionPassword(password))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseEntity<String> entity) {
                        mProgressDialog.hide();
                        if (entity != null) {
                            if (entity.isSuccess()) {
                                ToastUtils.showToast("支付成功");
                                startSignatureActivity(order_sn, goodName, realMoney, members_card);
                            } else {
//                                ToastUtils.showToast(entity.getMsg());
                                ToastUtils.showToast("支付不成功");
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mProgressDialog.hide();
                        ToastUtils.showToast("支付不成功");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void startSignatureActivity(String order_sn, String goodName, String realMoney, String memberCard) {
        if (mVerifyPasswordDialog != null && mVerifyPasswordDialog.isShowing()) {
            mVerifyPasswordDialog.dismiss();
        }
        if (mMemberInfoEntity.getMembers_type() == Constant.Member.MEMBER_PERSON) {
//            OrderDetailActivity.startActivity(mContext, order_sn, true);
            SignatureNameActivity.createOrderStartSignatureActivity(mContext, order_sn, goodName, realMoney, memberCard);
        } else {
            SignatureNameActivity.createOrderStartSignatureActivity(mContext, order_sn, goodName, realMoney, memberCard);
        }
    }

}
